package cases

import (
	"github.com/beego/beego/v2/client/orm"
	"time"
	"xpms/app/models"
	"xpms/cores"
	"xpms/cores/utils"
)

type TestCaseStep struct {
	Id              int64 `orm:"pk;column(stepid);" json:"Id,string"`
	Caseid          int64 `json:"Caseid,string"`
	Sort            int64
	Stepdesc        string
	Expectedresults string
	Results         string
	Remarks         string
	Created         int64
	Createid        int64 `json:"Createid,string"`
	Changed         int64
	Changid         int64 `json:"Changid,string"`
}

type TestCaseStepDto struct {
	Id              int64 `json:"Id,string"`
	Caseid          int64 `json:"Caseid,string"`
	Sort            int64
	Stepdesc        string
	Expectedresults string
	Results         string
	Remarks         string
	Created         int64
	Createid        int64 `json:"Createid,string"`
	Changed         int64
	Changid         int64 `json:"Changid,string"`
}

func (this *TestCaseStep) TableName() string {
	return models.TableName("projects_test_case_step")
}

func init() {
	orm.RegisterModel(new(TestCaseStep))
}

func AddCaseStep(upd TestCaseStep) error {
	o := orm.NewOrm()
	needs := new(TestCaseStep)

	needs.Id = upd.Id
	utils.SimpleCopyProperties(needs, upd)
	needs.Created = time.Now().Unix()
	_, err := o.Insert(needs)
	return err
}

func UpdateCaseStep(id int64, upd TestCaseStep) error {
	var needs TestCaseStep
	o := orm.NewOrm()
	needs = TestCaseStep{Id: id}
	utils.SimpleCopyProperties(needs, upd)
	needs.Changed = time.Now().Unix()
	_, err := o.Update(&needs)
	return err

}

func GetCaseStep(id int64) (TestCaseStep, error) {
	var needs TestCaseStep
	var err error
	o := orm.NewOrm()
	needs = TestCaseStep{Id: id}
	err = o.Read(&needs)

	if err == orm.ErrNoRows {
		return needs, nil
	}
	return needs, err
}

func GetCaseStepByCaseId(id int64) ([]TestCaseStep, error) {
	var Dto []TestCaseStep
	var err error
	o := orm.NewOrm()
	sql := "SELECT * FROM pms_projects_test_case_step WHERE caseid =?"
	_, err = o.Raw(sql, id).QueryRows(&Dto)
	if err == orm.ErrNoRows {
		return Dto, nil
	}
	return Dto, err
}
func TaskCaseStepByCaseIds(condArr map[string]interface{}) ([]TestCaseStep, error) {
	var Dto []TestCaseStep
	var err error
	o := orm.NewOrm()
	sql := `
    SELECT
		  step.*
		FROM pms_projects_test_pkg_case pc
		  INNER JOIN pms_projects_test_case tc ON tc.caseid=pc.caseid
		  INNER JOIN pms_projects_test_case_pkg pkg ON pkg.id=pc.pkgid
      INNER JOIN pms_projects_test_case_step step ON step.caseid=tc.caseid
      WHERE 1 = 1
    `
	param := make([]interface{}, 0, 0)
	if !utils.IsEmpty(condArr["pkgids"]) {
		sql = sql + ` pkg.id in(`
		sql1, value := cores.SqlInParam(condArr["pkgids"])
		sql = sql + sql1 + `)`
		param = append(param, value...)
	}
	_, err = o.Raw(sql, param).QueryRows(&Dto)
	if err == orm.ErrNoRows {
		return Dto, nil
	}
	return Dto, err
}
